package com.wm.wmim.connect.ws.interceptor;


import com.wm.wmim.common.constant.Constant;
import com.wm.wmim.connect.ws.rpcinvoke.UserInfoRpcInvokeService;
import com.wm.wmim.server.api.bo.resp.UserInfoBO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

import javax.annotation.Resource;
import java.util.Map;

/**
 * @author weiming
 * @date 2024/8/21 20:17
 * @description
 */
@Slf4j
@Component
public class WsHandshakeInterceptor implements HandshakeInterceptor {

    @Resource
    private UserInfoRpcInvokeService userInfoRpcInvokeService;

    @Override
    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {
        String queryString =  request.getURI().getQuery();
        log.info("[WsHandshakeInterceptor] beforeHandshake, param={}", queryString);
        if (queryString != null) {
            String[] queryParams = queryString.split("&");
            for (String queryParam : queryParams) {
                String[] keyValue = queryParam.split("=");
                if (keyValue.length == 2) {
                    attributes.put(keyValue[0], keyValue[1]);
                }
            }
        }
        // 鉴权
        Object userCodeObj = attributes.get(Constant.WsParamConstant.USER_CODE);
        if (userCodeObj == null) {
            log.info("[WsHandshakeInterceptor] 用户编码为空! param={}", queryString);
            return false;
        }
        String userCode = userCodeObj.toString();
        // TODO 鉴权方式修改
        UserInfoBO userInfoBO = userInfoRpcInvokeService.loginCheck(userCode);
        if (userInfoBO == null) {
            log.info("[WsHandshakeInterceptor] 登录校验失败! param={},res={}", queryString, userInfoBO);
            return false;
        }
        attributes.put(Constant.WsParamConstant.USER_INFO, userInfoBO);
        attributes.put(Constant.WsParamConstant.USER_ID, userInfoBO.getId());

        Object businessSceneObj = attributes.get(Constant.WsParamConstant.BUSINESS_SCENE);
        if (businessSceneObj == null) {
            return false;
        }
        String businessScene = businessSceneObj.toString();
        attributes.put(Constant.WsParamConstant.BUSINESS_SCENE, businessScene);

        return true;
    }

    @Override
    public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception exception) {
        // 设置一些参数
        log.info("[afterHandshake] start!");
    }
}
